package com.yangrd.airship.sys.web.modules.sys;

import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.StringExpression;
import com.yangrd.airship.common.jpa.BaseController;
import com.yangrd.airship.upms.domain.*;
import com.yangrd.airship.upms.support.AuthorizeDescribe;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: UserController
 *
 * @author: yangrd
 * @date: 2021/7/3
 * @version: 1.0
 */
@Api(tags = "系统管理-用户管理")
@AuthorizeDescribe({"系统管理", "用户管理"})
@RequiredArgsConstructor


@RestController
@RequestMapping("/api/sys/users")
public class UserController extends BaseController<User, Integer, UserRepository> {

    private final RoleRepository roleRepository;

    @Override
    public User save(@RequestBody User user) {
        List<Integer> roleIds = ((List<String>) user.getMeta().get("roleIds")).stream().map(Integer::valueOf).collect(Collectors.toList());
        List<Role> roles = roleRepository.findAllById(roleIds);
        user.setRoles(roles);
        return super.save(user);
    }

    @Override
    public void update(@PathVariable("id") User dbData, @RequestBody User user) {
        List<Integer> roleIds = ((List<String>) user.getMeta().get("roleIds")).stream().map(Integer::valueOf).collect(Collectors.toList());
        List<Role> roles = roleRepository.findAllById(roleIds);
        user.setRoles(roles);
        super.update(dbData, user);
    }

    @GetMapping
    @RolesAllowed("sys:users:view")
    public Page<User> findAll(@QuerydslPredicate(root = User.class, bindings = UserQueryDslBinderCustomizer.class) Predicate predicate, Pageable pageable) {
        return repository.findAll(predicate, pageable);
    }

    static class UserQueryDslBinderCustomizer implements QuerydslBinderCustomizer<QUser> {

        @Override
        public void customize(QuerydslBindings bindings, QUser qUser) {
            bindings.bind(qUser.username).first(StringExpression::contains);
        }
    }
}
